package com.wanxing.main;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.zhny.wxginger.R;


import android.app.ActionBar;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements OnClickListener,
		OnPageChangeListener {
	private View mActionBarView;
	private TextView title;
	private ViewPager mViewPager;
	private List<Fragment> mTabs = new ArrayList<Fragment>();
	private FragmentPagerAdapter mAdapter;
	private List<String> tagList = new ArrayList<String>();
	private List<ChangeColorIconWithText> mTabIndicators = new ArrayList<ChangeColorIconWithText>();
	private ActionBar actionBar;
	private android.app.FragmentManager fm =getFragmentManager();
	
	private long exitTime=0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		cusactionbar(); // 自定义actionbar
		
		initView(); // 動畫
		initDatas(title.getText().toString()); // important
		mViewPager.setAdapter(mAdapter); // add fragment to viewpaper ....
		initEvent();
//		mTabs.get(2).setOnButtonClick(new ControlFragment.OnButtonClick() {
//			//3、实现接口对象的方法�?
//			@Override
//			public void onClick(View view) {
//				//切换到TwoFragment
//				fm.beginTransaction()
//						//替换为TwoFragment
//						.replace(R.layout.fragment_container,new ())
//						.commit();
//			}
//		});

	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // overflow点击事件,改变fragment
		// TODO Auto-generated method stub
		if (item.isCheckable()) {
			item.setChecked(true);
		}
		int position;
		switch (item.getItemId()) {
		case R.id.no_1:
			title.setText("1号大棚");
			actionBar.setTitle("001");
			break;
		case R.id.no_2: 
			title.setText("2号大棚");
			actionBar.setTitle("002");
			break;
		case R.id.no_3:
			title.setText("6号大棚");
			actionBar.setTitle("006");
			break;
		default:
			// return super.onOptionsItemSelected(mi);
			break;
		}
		position = mViewPager.getCurrentItem();
		mViewPager.setAdapter(mAdapter);
		mViewPager.setCurrentItem(position);
		return true;
	}

	public void cusactionbar() {// 自定义actionbar
		actionBar = getActionBar();
		actionBar.setDisplayShowHomeEnabled(false); // 图标不显示
		setOverflowButtonAlways();
		mActionBarView = LayoutInflater.from(this).inflate(
						R.layout.actionbar_layout, null);
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
				ActionBar.LayoutParams.MATCH_PARENT,
				ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
		title = (TextView) mActionBarView.findViewById(R.id.title);
		actionBar.setCustomView(mActionBarView, lp);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setTitle("001");
	}

	/**
	 * 
	 */
	private void initEvent() {

		mViewPager.setOnPageChangeListener(this);

	}

	private void initDatas(String str) {
		DataShowFragment dataShowFragment = new DataShowFragment();
		DataAnalyzeFragment dataAnalyzeFragment = new DataAnalyzeFragment();
		ControlFragmentNew controlFragment = new ControlFragmentNew();
		SetorFragment setorFragment = new SetorFragment();
		mTabs.add(dataShowFragment);
		mTabs.add(dataAnalyzeFragment);
		mTabs.add(controlFragment);
		mTabs.add(setorFragment);

		mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

			@Override
			public int getCount() {
				return mTabs.size();
			}

			@Override
			public Fragment getItem(int position) {
				return mTabs.get(position);
			}

			@Override
			public void startUpdate(ViewGroup container) {  //更新容器viewpaper
				super.startUpdate(container);
				System.out.println("----startUpdate-----" );

			}

			@Override
			public void finishUpdate(ViewGroup container) {
				super.finishUpdate(container);
				System.out.println("----finishUpdate----");
			}

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();
                System.out.println("------notifyDataSetChanged-----");
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
                System.out.println("-------destroyItem--------" + position);
            }

            @Override
            public int getItemPosition(Object object) {
                System.out.println("--------getItemPosition-----");
                return super.getItemPosition(object);
            }

            @Override
            public long getItemId(int position) {
                return super.getItemId(position);
            }


        };

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void setOverflowButtonAlways() // 显示overflow
	{
		try {
			ViewConfiguration config = ViewConfiguration.get(this); // view配置
																	// configuration
			Field menuKey = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKey.setAccessible(true);
			menuKey.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initView() {
		mViewPager = (ViewPager) findViewById(R.id.id_viewpager);

		ChangeColorIconWithText one = (ChangeColorIconWithText) findViewById(R.id.id_indicator_one);
		mTabIndicators.add(one);
		ChangeColorIconWithText two = (ChangeColorIconWithText) findViewById(R.id.id_indicator_two);
		mTabIndicators.add(two);
		ChangeColorIconWithText three = (ChangeColorIconWithText) findViewById(R.id.id_indicator_three);
		mTabIndicators.add(three);
		ChangeColorIconWithText four = (ChangeColorIconWithText) findViewById(R.id.id_indicator_four);
		mTabIndicators.add(four);

		one.setOnClickListener(this);
		two.setOnClickListener(this);
		three.setOnClickListener(this);
		four.setOnClickListener(this);

		one.setIconAlpha(1.0f);

	}

	/**
	 * 改變menu的icon
	 */
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {

		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod(
							"setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return super.onMenuOpened(featureId, menu);
	}

	@Override
	public void onClick(View v) {
		clickTab(v);

	}

	/**
	 * 設置Tab
	 * 
	 * @param v
	 */
	private void clickTab(View v) {
		resetOtherTabs();

		switch (v.getId()) {
		case R.id.id_indicator_one:
			mTabIndicators.get(0).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(0, false);
			break;
		case R.id.id_indicator_two:
			mTabIndicators.get(1).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(1, false);
			break;
		case R.id.id_indicator_three:
			mTabIndicators.get(2).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(2, false);
			break;
		case R.id.id_indicator_four:
			mTabIndicators.get(3).setIconAlpha(1.0f);
			mViewPager.setCurrentItem(3, false);
			break;
		}
	}

	/**
	 * 閲嶇疆鍏朵粬鐨凾abIndicator鐨勯鑹 
	 */
	private void resetOtherTabs() {
		for (int i = 0; i < mTabIndicators.size(); i++) {
			mTabIndicators.get(i).setIconAlpha(0);
		}
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
		// Log.e("TAG", "position = " + position + " ,positionOffset =  "
		// + positionOffset);
		if (positionOffset > 0) {
			ChangeColorIconWithText left = mTabIndicators.get(position);
			ChangeColorIconWithText right = mTabIndicators.get(position + 1);
			left.setIconAlpha(1 - positionOffset);
			right.setIconAlpha(positionOffset);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){
			if((System.currentTimeMillis()-exitTime)>2000){
				Toast.makeText(MainActivity.this, "再点一次就让你退出去", Toast.LENGTH_SHORT).show();
				exitTime=System.currentTimeMillis();
			}else{
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrollStateChanged(int state) {
		// TODO Auto-generated method stub

	}

}
